package com.bw.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.bw.entity.user.TbUser;
import com.bw.req.TbUserRes;
import com.bw.resp.ResponseResult;
import com.bw.service.user.ITbUserService;

import com.bw.utils.auth.JwtUtils;
import com.bw.utils.auth.RsaUtils;
import com.bw.utils.auth.UserInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-05-09
 */
@RestController
@RequestMapping("user")
public class TbUserController {

    @Autowired
    private ITbUserService userService;

    @Value("${filePath}")
    private String filePath;


    /**
     * 用户列表信息接口
     */
    @GetMapping("get/{id}")
    public ResponseResult get(@PathVariable("id") Long id) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbUser user = userService.getById(id);
            result.setResult(user);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("查询1失败:" + e.toString());
        }
        return result;
    }


    /**
     * 用户列表信息接口
     */
    @PostMapping("list/{page}/{size}")
    public ResponseResult list(@PathVariable("page") int page, @PathVariable("size") int size, @RequestBody TbUserRes tbUserRes) { //参数json字符串
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PageHelper.startPage(page, size);//开启分页查询
            QueryWrapper queryWrapper = new QueryWrapper();
            if (null != tbUserRes.getFullName()) {
                queryWrapper.like("FULL_NAME", "%" + tbUserRes.getFullName() + "%");
            }
            if (null != tbUserRes.getStartDate() && null != tbUserRes.getEndDate()) {
                queryWrapper.between("HIREDATE", tbUserRes.getStartDate(), tbUserRes.getEndDate());
            }
            List<TbUser> users = userService.list(queryWrapper);//列表查询
            PageInfo pageInfo = new PageInfo(users);//pagehelper封装好的分页实体类，将数据放进去
            result.setResult(pageInfo);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("查询2失败:" + e.toString());
        }
        return result;
    }


    /**
     * 用户信息保存接口
     */
    @PostMapping("save")
    public ResponseResult save(@RequestBody TbUser tbUser) { //参数json字符串
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //判断用户名是否存在
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("USER_NAME", tbUser.getUserName());
            List<TbUser> users = userService.list(queryWrapper);
            if (users.size() > 0 && null == tbUser.getId()) {//如果查询用户名存在则提示用户
                result.setSuccess(false);
                result.setMessage("保存失败:用户名已存在");
                return result;
            }
            tbUser.setPwd("123456");//注册的时候默认密码123456
            tbUser.setIsEnable(1);//默认是启用状态
            userService.saveOrUpdate(tbUser);//添加或修改用户信息
            result.setMessage("保存成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("保存失败:" + e.toString());
        }
        return result;
    }
    /**
     * 用户列表信息接口
     */
    @GetMapping("updateIsEnable/{id}/{isEnable}")
    public ResponseResult updateIsEnable(@PathVariable("id") Long id, @PathVariable("isEnable") Integer isEnable) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbUser user = userService.getById(id);
            user.setIsEnable(isEnable);
            userService.saveOrUpdate(user);
            result.setMessage("修改成功");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("修改失败:" + e.toString());
        }
        return result;
    }

    /**
     * 用户登录接口
     */
    @PostMapping("/login")
    public ResponseResult login(@RequestBody TbUser tbUser) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            //判断用户名密码
            QueryWrapper queryWrapper=new QueryWrapper();
            Map map=new HashMap<>();
            map.put("USER_NAME",tbUser.getUserName());
            map.put("PWD",tbUser.getPwd());
            queryWrapper.allEq(map);
           List<TbUser> tbUsers=userService.list(queryWrapper);
            //正确登录
            if(tbUsers.size()>0){
                TbUser user=tbUsers.get(0);
                PrivateKey privateKey = RsaUtils.getPrivateKey("D:\\jwt\\key\\rsa.pri");//获取私钥

                UserInfo userInfo=new UserInfo(); //当前登录用户信息
                userInfo.setId(user.getId());
                userInfo.setUsername(user.getUserName());

                String token = JwtUtils.generateToken(userInfo,privateKey,360);//颁发令牌

                Map mapinfo=new HashMap();
                mapinfo.put("user",user);
                mapinfo.put("token",token);

                result.setMessage("登录成功");
                result.setResult(mapinfo);


            }else{
                //错误提示
                result.setMessage("用户或密码错误");
                result.setSuccess(false);
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("登录异常:" + e.toString());
        }
        return result;
    }

    /**
     * 用户头像上传接口
     */
    @PostMapping("upload")
    public ResponseResult upload(MultipartFile file) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
                //1，获取文件后缀
            String ext=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."),file.getOriginalFilename().length());
                //2，获取路径
            String dirPath=filePath;
            String path=UUID.randomUUID()+ext;
                //3，将文件复制到对应服务器的路径下
            File mFile=new File(dirPath+path);
            file.transferTo(mFile);
                //4，将文件的存储路径返回给前端

            Map map=new HashMap();
            map.put("path",path);
            result.setResult(map);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage("上传失败:" + e.toString());
        }
        return result;
    }

    /**
     * 文件下载接口
     */
    @GetMapping("download/{path}")
    public void download(@PathVariable("path") String path, HttpServletResponse response) {
        if(null==path){
            return;
        }
        try {
            //读取图片文件流
            InputStream inputStream=new FileInputStream(filePath+path);

            byte[] b=new byte[1024];//定义每次读取输入流当中的多少字节
            int len;//记录每次读取字节流的位置

            while ((len=inputStream.read(b))>0){            //将文件流写到响应输出流当中
                response.getOutputStream().write(b,0,len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
